package com.qf.config;

import com.qf.util.JwtUtils;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private JwtUtils jwtUtils;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token=jwtUtils.getToken(request);
        if (!ObjectUtils.isEmpty(token) && SecurityContextHolder.getContext().getAuthentication() == null) {
            //验证token
            jwtUtils.validateToken(token);
            //验证成功,刷新令牌时间
            jwtUtils.refreshToken(token);
            Claims claims=jwtUtils.parseJwt(token);
            List<String> authorities=claims.get("perms",List.class);
            // 字符串使用指定的符号拼接成一个完整的字符串
            String authoritiesString = String.join(",", authorities);
            UsernamePasswordAuthenticationToken authenticationToken =
                    new UsernamePasswordAuthenticationToken(claims.get("username"),
                            null,
                            AuthorityUtils.commaSeparatedStringToAuthorityList(authoritiesString));
            authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            //放入上下文
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        }
        filterChain.doFilter(request,response);
    }
}
